package com.orangelife.mobile.goodsOrder.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.http.OrangeDataHandler;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.goodsOrder.adapter.GoodsOrderAdapter;
import com.orangelife.mobile.goodsOrder.biz.OrderBiz;
import com.orangelife.mobile.goodsOrder.biz.OrderHttp;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 全部订单
 * Created by YangWei
 * on 2016/1/14.
 */
public class AllOrderActivity extends OrangeLifeBaseActivity implements View.OnClickListener {
    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_title_right)
    ImageView ivTitleRight;
    @Bind(R.id.lv_my_order)
    PullToRefreshListView lvMyOrder;
    @Bind(R.id.tvNoBill)
    TextView tvNoBill;
    @Bind(R.id.llPropertyBillN)
    RelativeLayout llPropertyBillN;
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    private int pageNo = Constant.PAGE_NO_DEFAULT;

    private GoodsOrderAdapter<Map<String, Object>> adapter;
    private List<Map<String, Object>> list, list2;
    private Handler mHandler;
    private Dialog dialog;
    private int flags = 1;//分辨是刷新还是加载更多
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_all);
        ButterKnife.bind(this);
        isNoBill(false);
        initView();
    }

    private void initView() {
        mHandler = new Handler();
        tvTitle.setText("全部订单");
        tvNoBill.setText("您目前没有订单");
        getDataFromServer();
        getMyGoodsOrderList();
        setAdapter();
        pullListView();
        ivTitleRight.setOnClickListener(this);

    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        list = new ArrayList<Map<String, Object>>();
        list2 = new ArrayList<Map<String, Object>>();
        adapter = new GoodsOrderAdapter<Map<String, Object>>(this, list);
        adapter.showDate(true);
        lvMyOrder.setPullLoadEnable(false);
        lvMyOrder.setAdapter(adapter);

        adapter.setJump(new GoodsOrderAdapter.jumpInterface() {
            @Override
            public void pay(Map<String, Object> map) {
                OrderBiz.payOrder(map,AllOrderActivity.this,null);
            }

            @Override
            public void confirm(final String orderId) {
                final ConfirmDialog dialog = new ConfirmDialog(AllOrderActivity.this, "", "确认收货后将不再支持退款申请，\n" +
                        "是否确认收货？", "取消", "确认");
                dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        dialog.dismiss();
                    }

                    @Override
                    public void doRight() {
                        dialog.dismiss();
                        getDataFromServer();
                        OrderHttp.postConfirmRequest(orderId, handler);
                    }
                });
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }

            @Override
            public void backGood(String applicationID) {
                OrderBiz.backGoods(applicationID,AllOrderActivity.this);
            }
        });

    }
    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 500:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    DialogHelper.closeDialog(dialog);
                    break;
                case 1001:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    isLogin(dialog);
                    break;
                case 1:
                    list2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);
                    updateListView(list2);
                    break;
                case OrderBiz.CONFIRM_GOOD:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.submit_success));
                        OrderHttp.getOrderMsgNum(handler);
                        pageNo = 1;
                        list.clear();
                        getMyGoodsOrderList();
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaintes_sumbite_fail));
                    }
                    break;
                default:
                    break;
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        }

    };
    /**
     * 获取我的商品订单列表
     */
    private void getMyGoodsOrderList() {
        OrderHttp.getMyGoodsOrderList("", 0,  pageSize, pageNo,handler);
    }


    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvMyOrder.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getMyGoodsOrderList();
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getMyGoodsOrderList();
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvMyOrder.stopRefresh();
        lvMyOrder.stopLoadMore();
        lvMyOrder.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {

        boolean havebill = false;
        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    lvMyOrder.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = false;
                } else {
                    lvMyOrder.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            } else {
                if (flags == 1) {
                    list.clear();
                    lvMyOrder.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                } else {
                    lvMyOrder.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            }
        } else {
            lvMyOrder.setPullLoadEnable(false);
            havebill = false;
        }
        isNoBill(havebill);
    }
    /**
     * 判断是否有订单显示无订单页面
     *
     * @param havebill
     */
    private void isNoBill(boolean havebill) {
        if (havebill) {
            lvMyOrder.setVisibility(View.VISIBLE);
            llPropertyBillN.setVisibility(View.GONE);
        } else {
            lvMyOrder.setVisibility(View.GONE);
            llPropertyBillN.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        IntentHelper.getInstances().bundleWithBundleForResult(this,SearchOrderActivity.class,null,0);
    }
}
